package com.sl.utils.encryptionAlgorithm;

import com.alibaba.fastjson.JSONObject;
import com.sl.utils.deepClone.Car;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author ：zhangC
 * @date ：Created in 2020/9/15 14:54
 * @description：AES加解密工具类
 * @version: $2.0
 */
@Slf4j
public class OldAESUtils {
    private static int Length = 128;
    /**
     * 加密密码 必须是16个字节长度
     */
    public static final String strKey = "mingduWMSLicense";
    /**
     * 随机生成的加密密码 每次生成的byte[]却是不同的
     */
    private static byte[] password = generateKey();

    public static void main(String[] args) {
        Car car = new Car();
        car.setBrand("public_password1234");
        car.setMaxSpeed(11);
        String password = OldAESUtils.strKey;
        System.out.println(password);

        //加密
        System.out.println("加密前：" + car);
//        String encryptResult = OldAESUtils.encrypt(JSONObject.toJSONString(car));
        String encryptResult = OldAESUtils.encrypt("2020-09-24 10:02:27");
        System.out.println(encryptResult);

        //解密
        String s = parseByte2HexStr("U2FsdGVkX1+F1r54HdlCn3Slr56Yqncu0z83gv/Rrq9PB3onE2fO9Ebmd0G+5p3i".getBytes());
//        String decryptResult = OldAESUtils.decrypt("U2FsdGVkX1+F1r54HdlCn3Slr56Yqncu0z83gv/Rrq9PB3onE2fO9Ebmd0G+5p3i");
        String decryptResult = OldAESUtils.decrypt(s);
        System.out.println("s：" +s);
        System.out.println("解密"+decryptResult);

//        Car entity1 = JSONObject.parseObject(decryptResult, Car.class);
//        System.out.println("解密后：" + entity1);
    }

    /**
     * 注意：即便strKey相同 但是每次生成的byte[]却是不同的
     *
     * @param strKey
     * @return 16Byte的加密password
     */
    public static byte[] generateKey() {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            generator.init(Length, secureRandom);
            return generator.generateKey().getEncoded();
        } catch (NoSuchAlgorithmException e) {
            log.error(e.toString());
        }
        return null;
    }

    /**
     * 加密
     * @param content
     * @return
     */
    public static String encrypt(String content) {
        return encrypt(content, strKey);
    }

    /**
     * 加密，传入加密后的密码
     * @param content
     * @param strKey
     * @return
     */
    public static String encrypt(String content, String strKey) {
        try {
            //初始化密钥 SecretKeySpec(byte[] key, String algorithm)
            SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
            //创建密码器
            Cipher cipher = Cipher.getInstance("AES");
            //初始化 key要求是16位 16个字节=16*8=128bit 128位
            cipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] byteContent = content.getBytes("utf-8");
            //获取加密后字节数组
            byte[] result = cipher.doFinal(byteContent);

            //获取加密后的字符串
            return parseByte2HexStr(result);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return null;
    }

    /**
     * 解密
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        return decrypt(content, strKey);
    }

    /**
     * 解密，传入加密后的密码
     * @param content
     * @param strKey
     * @return
     */
    public static String decrypt(String content, String strKey) {
        try {
            SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES");
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(parseHexStr2Byte(content));
            // 明文
            return new String(result);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return null;
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr 字符串
     * @return 字节数组
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf 字节数组
     * @return 字符串
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}